package gui.user;

import info.Passenger;
import messages.user.RegisterRequestMessage;
import messages.user.RegisterResponseMessage;
import server.MessageServer;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.util.regex.Pattern;

public class RegisterForm extends JFrame {
    private JTextField phoneField;
    private JTextField identityNumTextField;
    private JTextField nameField;
    private JPasswordField passwordField;
    private JPasswordField surePasswordField;
    private JButton sureButton;
    public RegisterForm(){
        super("注册");
        setSize(450, 300);

        JPanel registerPanel = new JPanel(new GridLayout(6, 2));

        registerPanel.add(new JLabel("身份证:",JLabel.CENTER));
        identityNumTextField = new JTextField(20);
        registerPanel.add(identityNumTextField);

        registerPanel.add(new JLabel("手机号码:",JLabel.CENTER));
        phoneField = new JTextField(20);
        registerPanel.add(phoneField);

        registerPanel.add(new JLabel("姓名:",JLabel.CENTER));
        nameField = new JTextField(20);
        registerPanel.add(nameField);

        registerPanel.add(new JLabel("密码:",JLabel.CENTER));
        passwordField = new JPasswordField(20);
        registerPanel.add(passwordField);

        registerPanel.add(new JLabel("确认密码:",JLabel.CENTER));
        surePasswordField = new JPasswordField(20);
        registerPanel.add(surePasswordField);

        sureButton = new JButton("注册");
        sureButton.addActionListener(e -> {
            String idNum = identityNumTextField.getText();
            String name = nameField.getText();
            String telephone = phoneField.getText();
            String pwd = new String(passwordField.getPassword());
            String surePwd = new String(surePasswordField.getPassword());

            if(idNum.isEmpty() || telephone.isEmpty() || pwd.isEmpty() || surePwd.isEmpty()){
                JOptionPane.showMessageDialog(this,"所有字段都必须填写");
                return;
            }

            if(!isValidIDCard(idNum)){
                JOptionPane.showMessageDialog(this,"身份证输入格式不正确");
                return;
            }

            if(!isValidPhoneNumber(telephone)){
                JOptionPane.showMessageDialog(this,"手机号码输入格式不正确");
                return;
            }

            if(!pwd.equals(surePwd)){
                JOptionPane.showMessageDialog(this,"密码和确认密码输入不一致");
                return;
            }

            Passenger passenger = new Passenger(idNum,pwd,name,telephone);
            if(sendRegisterRequest(passenger)){
                JOptionPane.showMessageDialog(this, "注册成功！");
                this.dispose();
            }else{
                JOptionPane.showMessageDialog(this, "该身份证已经注册！请重新输入");
            }
        });

        registerPanel.add(new JLabel(""));
        registerPanel.add(sureButton);

        add(registerPanel);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private final String ID_CARD_REGEX =
            "^[1-9]\\d{5}(18|19|20)?\\d{2}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\\d{3}[0-9Xx]$";
    private final int[] WEIGHTS = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    private final char[] CHECK_CODES = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
    private final String PHONE_REGEX = "^1[3-9]\\d{9}$";


    private boolean isValidIDCard(String idCard) {
        if (!Pattern.matches(ID_CARD_REGEX, idCard)) {
            return false;
        }
        char[] chars = idCard.toCharArray();
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            sum += (chars[i] - '0') * WEIGHTS[i];
        }
        char checkCode = CHECK_CODES[sum % 11];
        return checkCode == chars[17];
    }

    private boolean isValidPhoneNumber(String phone) {
        return Pattern.matches(PHONE_REGEX, phone);
    }

    private boolean sendRegisterRequest(Passenger passenger){
        if (!MessageServer.getInstance().isConnected()) {
            int maxRetry = 10, j = 0;
            while (j++ < maxRetry) {
                if(MessageServer.getInstance().connectToServer())
                    break; // 连接成功
            }
        }

        RegisterRequestMessage register_req_msg = new RegisterRequestMessage(passenger);
        RegisterResponseMessage register_ack_msg;

        try {
            MessageServer.getInstance().getOos().writeObject(register_req_msg);
            System.out.println("客户端发送请求成功！"+register_req_msg);
            register_ack_msg = (RegisterResponseMessage) MessageServer.getInstance().
                    getOis().readObject();
            System.out.println("客户端收到服务端的响应成功！"+register_ack_msg);
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        if(register_ack_msg.isSuccess()){
            return true;
        }else {
            return false;
        }
    }
}
